package org.example.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.dao.SubmissionsDao;
import org.example.pojo.Submissions;
import org.example.service.processingJudgingResults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Component
public class GetResultSchedule {

    @Autowired
    private SubmissionsDao submissionsDao;

    @Autowired
    private processingJudgingResults processingJudgingResults;
    //引入锁
    private static ReentrantLock reentrantLock = new ReentrantLock();

    @Scheduled(cron = "0/1 * *  * * ?")
    public void getProblemResult(){


        //加锁
        if(reentrantLock.tryLock()){
            try {
                //轮询数据库，查看判题结果，如果judgement_result值不为null,返回Submissions和tokens
                List<Submissions> submissions = submissionsDao.selectList(
                        new QueryWrapper<Submissions>()
                                .ne("judgment_result", ""));

                //删除已经判题过的题目信息
                if (!submissions.isEmpty()) {


                    // 批量删除已经判题过的题目信息
                    submissionsDao.deleteBatchIds( submissions.stream().map(Submissions::getId).collect(Collectors.toList()));

                    //TODO 进行结果整理与返回结果,多线程异步
                    processingJudgingResults.GetProcessingJudgingResults(submissions);


                }

            }catch (Exception e){
                // 处理异常，可以记录日志或进行其他操作
                e.printStackTrace();

            }finally {
                //解锁
                reentrantLock.unlock();
            }

        }





    }



}
